﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using PineLake.Drmwe.Lib.ResultMsg;
using PineLake.Drmwe.Lib.EnumText;
using System.Text;
using Microsoft.AspNetCore.Mvc.Controllers;

namespace RepositoryMultipleDataBases.Filters
{
    /// <summary>
    /// 实体模型验证过滤器
    /// </summary>
    public class ModelValidateActionFilter : ActionFilterAttribute
    {
        public ModelValidateActionFilter()
        {
            Order = int.MinValue;
        }

        ///// <summary>
        ///// 重写实体模型验证过滤器
        ///// </summary>
        ///// <param name="context"></param>
        //public override void OnActionExecuting(ActionExecutingContext context)
        //{
        //    if (!context.ModelState.IsValid)
        //    {
        //        var Errors = context.ModelState
        //            .Where(e => e.Value.Errors.Count > 0)
        //            .Select(e => new
        //            {
        //                Message = e.Value.Errors.First().ErrorMessage,
        //                Field = e.Key,
        //            })
        //            .ToList();

        //        var ErrorToString = string.Join(",", Errors.Select(a => $"参数: {a.Field}, {a.Message}").ToList());
        //        //设置返回内容
        //        var result = new ApiResultMsg()
        //        {
        //            StatusCode = (int)ApiStatusCodeEnum.ParameterError,
        //            Data = ErrorToString,
        //            Info = ApiStatusCodeEnum.ParameterError.GetEnumText()
        //        };
        //        //返回状态码
        //        context.Result = new JsonResult(result);
        //        context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
        //    }
        //    base.OnActionExecuting(context);
        //}

        /// <summary>
        /// 重写实体模型验证过滤器
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (!context.ModelState.IsValid)
            {
                var Errors = context.ModelState
                    .Where(e => e.Value.Errors.Count > 0)
                    .Select(e => new
                    {
                        Message = e.Value.Errors.First().ErrorMessage,
                        Field = e.Key,
                    })
                    .ToList();

                var ErrorToString = string.Join(",", Errors.Select(a => $"参数: {a.Field}, {a.Message}").ToList());
                //设置返回内容
                var result = new ApiResultMsg()
                {
                    StatusCode = (int)ApiStatusCodeEnum.ParameterError,
                    Data = ErrorToString,
                    Info = ApiStatusCodeEnum.ParameterError.GetEnumText()
                };
                //返回状态码
                context.Result = new JsonResult(result);
                context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
            }
            await base.OnActionExecutionAsync(context, next);
        }
        ///// <summary>
        ///// 读取action返回的result
        ///// </summary>
        ///// <param name="actionExecutedContext"></param>
        ///// <returns></returns>
        //public string GetResponseValues(ActionExecutingContext context)
        //{
        //    var BR = context.Result;
        //    Stream stream = context.HttpContext.
        //    Encoding encoding = Encoding.UTF8;
        //    /*
        //    这个StreamReader不能关闭，也不能dispose， 关了就傻逼了
        //    因为你关掉后，后面的管道  或拦截器就没办法读取了
        //    */
        //    var reader = new StreamReader(stream, encoding);
        //    string result = reader.ReadToEnd();
        //    /*
        //    这里也要注意：   stream.Position = 0; 
        //    当你读取完之后必须把stream的位置设为开始
        //    因为request和response读取完以后Position到最后一个位置，交给下一个方法处理的时候就会读不到内容了。
        //    */
        //    stream.Position = 0;
        //    return result;
        //}
    }
}
